package org.hw.Interceptor;

import io.netty.util.internal.StringUtil;
import org.hw.entity.Session;
import org.hw.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedHashMap;

public class UserLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;

    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了拦截器的preHandle方法");
        String token = request.getHeader("token");
        if (StringUtil.isNullOrEmpty(token)) {
            throw new CustomerException(400, "缺少token");
        }
        System.out.println("有token"+token);
        LinkedHashMap hashMap = (LinkedHashMap) redisUtil.get("session_" + token);
        System.out.println("hashMap:"+ hashMap);
        if(hashMap==null){
            throw new CustomerException(400, "请先登陆");
        }
        Session sessionData = new Session();
        sessionData.setUnitId(String.valueOf(hashMap.get("unitId")));
        // Convert Long to String using String.valueOf()
        sessionData.setUserId(String.valueOf(hashMap.get("userId")));
        sessionData.setUserName(String.valueOf(hashMap.get("userName")));
        sessionData.setPlatform(String.valueOf(hashMap.get("platform")));
        sessionData.setType(hashMap.get("type") + "");
        sessionData.setAddress(String.valueOf(hashMap.get("address")));
        sessionData.setInTime(String.valueOf(hashMap.get("inTime")));
        sessionData.setCreateTime(Long.valueOf(String.valueOf(hashMap.get("createTime"))));
        if (sessionData.getUserId() == null) {
            throw new CustomerException(400, "请重新登录");
        } else if (System.currentTimeMillis() - sessionData.getCreateTime() > 2 * 60 * 60 * 1000) {
            throw new CustomerException(400, "登录已过期");
        } else {
            request.setAttribute("session", sessionData);
        }
        return true;
        //如果设置为false时，被请求时，拦截器执行到此处将不会继续操作
        //如果设置为true时，请求将会继续执行后面的操作
    }

    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("执行了拦截器的postHandle方法");
    }

    /***
     * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //System.out.println("执行了拦截器的afterCompletion方法");
    }
}